﻿using System;
using System.IO;
using CommonFramework.Serialize.BytesArray.Private;

namespace CommonFramework.Serialize.BytesArray
{
    public class BytesBuffer
    {
        public const int INIT_BUFFER_SIZE = 1024;
        public const int PER_CHUNK_SIZE = 65536;

        private BytesExtender _extender;
        private void InitBytesExtender(byte[] initBytes,int offset,int count)
        {
            _extender?.Clear();
            _extender = new BytesExtender(initBytes, offset, count);
        }
        public byte[] Bytes => _extender.CurrentBytes();
        public int DataLength() => _extender.DataLength();
        public int DataStart() => _extender.ReadIndex;
        public int TotalLength() => _extender.TotalLength();

        public BytesBuffer(int initLength= INIT_BUFFER_SIZE)
        {
            InitBytesExtender(null,0,initLength);
        }
        public BytesBuffer(byte[] initBytes)
        {
            InitBytesExtender(initBytes, 0, initBytes.Length);
        }
        public BytesBuffer(byte[] initBytes, int offset,int count)
        {
            InitBytesExtender(initBytes, offset,count);
        }

        protected BytesReader _reader;
        public BytesReader GetReader()
        {
            return _reader ?? (_reader = new BytesReader(_extender));
        }

        protected BytesWriter _writer;
        public BytesWriter GetWriter()
        {
            return _writer ?? (_writer = new BytesWriter(_extender));
        }

        public byte[] ToBytes()
        {
            var reader = GetReader();
            byte[] data = new byte[reader.DataLength()];
            reader.ReadBytes(data);
            return data;
        }

        public void ToStream(Stream stream)
        {
            if (stream == null || !stream.CanWrite)
                throw new ArgumentException("stream should be writeable");

            var reader = GetReader();
            reader.ReadStream(stream, reader.DataLength());
        }
    }
}